<template>
  <div class="transformJson">
    <div class="transformJson-origin">
      <Textarea
        width="100%"
        height="100%"
        placeholder="请输入JSON字符串"
        v-model="originValue"
        @input="changeOriginTextareaValue"
        :validator="validatorJson"
      >
      </Textarea>
    </div>
    <div class="transformJson-origin">
      <Textarea width="100%" height="100%" v-model="targetValue">
        <div class="transformJson-origin-header">
          <i class="iconfont iconfuzhi" @click="copyJson"></i></div
      ></Textarea>
    </div>
  </div>
</template>

<script setup lang="ts">
import Textarea from "@/components/Textarea/index.vue";
import { copy, jsonBeautiful, safeJsonParse } from "@/util/util";
import { ref } from "vue";

const originValue = ref<string>(""); // 源数据值
const targetValue = ref<string>(""); // 解析后数据值

// 修改源数据
const changeOriginTextareaValue = () => {
  const formatJson = jsonBeautiful(originValue.value);
  originValue.value = formatJson!;
  const expData = formatJson
    .replace(/integer\[.+\]/g, "number")
    .replace(/string\[date\]/g, "string")
    .replace(/\s\"(.+) (\[.+\])\"\: \"(.+)\"/g, "$1: $3 // $2")
    .replace(/(\s*)\"(.+)(\[.+\])\"\: (\{)/g, "$1$2: $4 // $3")
    .replace(/(\s*)\"(.+)(\[.+\])\"\: (\[)/g, "$1$2: $4 // $3");
  targetValue.value = expData;
};

// 校验JSON是否正确
const validatorJson = () => {
  if (!originValue.value) {
    return Promise.resolve();
  }
  const { success } = safeJsonParse(originValue.value);
  return success ? Promise.resolve() : Promise.reject("JSON格式错误");
};

// 复制json
const copyJson = () => {
  copy(targetValue.value);
};
</script>

<style lang="scss" scoped>
@import "./style.scss";
</style>
